﻿
var categoryId = $('.filterBox input[name$=hidCategoryId]').val();
$(function () {
    // load slider
    LoadSliderPriceRange();
    // load rate slider
    LoadSliderRate();
    // Quick search
    quickSearchFilterbox();

    // set height provider
    setHeightProviderFilBox();
    // set height Color
    setHeightColorFilBox();
    // set kich thuoc cho box Size
    setHeightSizeFilBox();
    // set kich thuoc cho box Attr
    setHeightAttrFilBox();

    // ITEM CLICK 
    // provider click
    ProviderItemClick();
    // Color click
    ColorItemClick();
    // Size click
    SizeItemClick();
    // Attr click
    AttrItemClick();
});

// HEIGHT=====================================================================================
// set kich thuoc cho box provider
function setHeightProviderFilBox() {
    var hProvider = $('input[name$=hidHeightProvider]').val();
    var hProviderCurrent = $('.ListProviderFil ul li').size();
    if (hProvider != "0") {
        if (hProviderCurrent < parseInt(hProvider)) {
            $('.ListProviderFil ul').removeAttr('style');
        } else {
            $('.ListProviderFil ul').attr('style', 'height:' + (parseInt(hProvider) * 30) + 'px');
        }
    }
}

// set kich thuoc cho box COLOR
function setHeightColorFilBox() {
    var hColor = $('input[name$=hidHeightColor]').val();
    var hColorCurrent = $('.ColorFil ul li').size();
    if (hColor != "0") {
        if (hColorCurrent < parseInt(hColor)) {
            $('.ColorFil ul').removeAttr('style');
        } else {
            $('.ColorFil ul').attr('style', 'height:' + (parseInt(hColor) * 25) + 'px');
        }
    }
}

// set kich thuoc cho box Size
function setHeightSizeFilBox() {
    var hSize = $('input[name$=hidHeightSize]').val();
    var hSizeCurrent = $('.SizeFil ul li').size();
    if (hSize != "0") {
        if (hSizeCurrent < parseInt(hSize)) {
            $('.SizeFil ul').removeAttr('style');
        } else {
            $('.SizeFil ul').attr('style', 'height:' + (parseInt(hSize) * 25) + 'px');
        }
    }
}

// set kich thuoc cho box Attr
function setHeightAttrFilBox() {
    var hAttr = $('input[name$=hidHeightAttr]').val();
    var hAttrCurrent = $('.AttrFil ul li').size();
    if (hAttr != "0") {
        if (hAttrCurrent < parseInt(hAttr)) {
            $('.AttrFil ul').removeAttr('style');
        } else {
            $('.AttrFil ul').attr('style', 'height:' + (parseInt(hAttr) * 25) + 'px');
        }
    }
}

// EVENT SLIDE AND RATE ===============================================================================
function quickSearchFilterbox() {
    $('input#ProviderSearch').quicksearch('.ListProviderFil ul li');
}

// hieu ung slide star
function LoadSliderRate() {
    // RATE - SLIDER
    var CmdrateFil = $('.Rate-fil input[name$=hidRateRil]');
    var rateFil = new Array('1', '5');
    if (CmdrateFil.val() != undefined) {
        rateFil = CmdrateFil.val().split(';');
    }
    var rateMin = 0;
    var rateMax = 5;
    rateMin = (parseInt(rateFil[0]) - 1) * 25;
    rateMax = (parseInt(rateFil[1]) - 1) * 25;
    $("#ecg-slider-rate").slider({
        orientation: "vertical",
        range: true,
        min: 0,
        max: 100,
        step: 25,
        values: [rateMin, rateMax],
        slide: function (event, ui) {
            var ratemin = (parseInt(ui.values[0]) / 25) + 1;
            var ratemax = (parseInt(ui.values[1]) / 25) + 1;
            $("#rateValueMin").val(ratemin);
            $("#rateValueMax").val(ratemax);

            //hieu ung lam mo sao
            $('.listStarFil ul li').find('.itm-ratRating').removeClass('starNone');
            $('.listStarFil ul li:gt(' + (5 - ratemin) + ')').find('.itm-ratRating').addClass('starNone');
            $('.listStarFil ul li:lt(' + (5 - ratemax) + ')').find('.itm-ratRating').addClass('starNone');

            // hien thi nut tim kiem: hien thi 10s roi an di

            //$('#plcRateRil input[name$=btnRateRil]').stop(true, true).fadeOut().fadeIn();
            //$('#plcRateRil input[name$=btnRateRil]').attr('title', 'Tất cả sản phẩm từ ' + ratemin + ' sao đến ' + ratemax + ' sao');
        },
        change: function (event, ui) {
            //  rate click
            bindDataFilterAjax();
        }
    });
    $("#rateValueMin").val(parseInt(($("#ecg-slider-rate").slider("values", 0)) / 25) + 1);
    $("#rateValueMax").val(parseInt(($("#ecg-slider-rate").slider("values", 1)) / 25) + 1);
    //$('#plcRateRil input[name$=btnRateRil]').attr('title', 'Tất cả sản phẩm từ ' + (parseInt(($("#ecg-slider-rate").slider("values", 0)) / 25) + 1) + ' sao đến ' + (parseInt(($("#ecg-slider-rate").slider("values", 1)) / 25) + 1) + ' sao');

}

// hieu ung slider price
function LoadSliderPriceRange() {
    var srrPriceRang = $('.PriceRangeFil input[name$=hidPriceRang]').val().split(';');
    var step = parseInt(srrPriceRang[4]);
    var pMin = parseInt(srrPriceRang[0]);
    var pMinDefault = parseInt(srrPriceRang[2]);
    if (srrPriceRang.length > 0) {
        if (srrPriceRang[2] == srrPriceRang[3]) {
            step = parseInt(srrPriceRang[2]);
            pMin = 0;
            pMinDefault = 0;
        }
    }
    // Slider price
    $("#ecg-slider").slider({
        range: true,
        min: pMin,
        max: parseInt(srrPriceRang[1]),
        step: step,
        values: [pMinDefault, parseInt(srrPriceRang[3])],
        slide: function (event, ui) {
            if (srrPriceRang[2] == srrPriceRang[3]) {
                $("#priceMin").val(srrPriceRang[2]);
                $("#hidpriceMin").val(srrPriceRang[2]);
            } else {
                $("#priceMin").val(ui.values[0]);
                $("#hidpriceMin").val(ui.values[0]);
            }
            $("#priceMax").val(ui.values[1]);
            $("#hidpriceMax").val(ui.values[1]);
            // Digits
            toSplitNumberByComma($('#priceMax'));
            toSplitNumberByComma($('#priceMin'));
            //$('.btnFil').attr('title', 'Lọc theo giá từ ' + formatNumber(ui.values[0]) + ' vnđ đến ' + formatNumber(ui.values[1]) + ' vnđ');

            $(event)
        },
        change: function (event, ui) {
            //  Price click
            bindDataFilterAjax();
        }
    });
    //hien thi gia tri hien tai
    if (srrPriceRang[2] == srrPriceRang[3]) {
        $("#priceMin").val(srrPriceRang[2]);
        $("#hidpriceMin").val(srrPriceRang[2]);
    } else {
        $("#priceMin").val($("#ecg-slider").slider("values", 0));
        $("#hidpriceMin").val($("#ecg-slider").slider("values", 0));
    }

    $("#priceMax").val($("#ecg-slider").slider("values", 1));
    $("#hidpriceMax").val($("#ecg-slider").slider("values", 1));
    //$('.btnFil').attr('title', 'Lọc theo giá từ ' + formatNumber($("#ecg-slider").slider("values", 0)) + ' vnđ đến ' + formatNumber($("#ecg-slider").slider("values", 1)) + ' vnđ');

    // Digits
    toSplitNumberByComma($('#priceMax'));
    toSplitNumberByComma($('#priceMin'));
}

// remove price param
function removeUrlPrice() {
    removeDataFilterAjax('price');
}

// remove rate param
function removeUrlRate() {
    removeDataFilterAjax('rate');
}

// remove price param
function removeUrlProvider() {
    removeDataFilterAjax('provider');
}

// remove rate param
function removeUrlColor() {
    removeDataFilterAjax('color');
}

// remove rate param
function removeUrlSize() {
    removeDataFilterAjax('size');
}

// remove rate param
function removeUrlAttr() {
    removeDataFilterAjax('attr');
}

// EVENT CLICK ITEM ===================================================================================
// provider click
function ProviderItemClick() {
    $('.ListProviderFil ul li input[type=checkbox]').click(function () {
        var boolChk = false;  // true is checked
        $('.ListProviderFil ul li input[type=checkbox]:checked').each(function (index) {
            boolChk = true;
        });

        if (!boolChk) {
            removeDataFilterAjax('provider'); // bi remove url Attr
        } else {
            bindDataFilterAjax();
        }
    });
}

// Color click
function ColorItemClick() {
    $('.ColorFil ul li input[type=checkbox]').click(function () {
        var valueParam = '';
        var boolChk = false; //kiem tra xem co checked nao ko, neu ko co hien thi toan bo checked len

        $('.ColorFil ul li input[type=checkbox]:checked').each(function (index) {
            boolChk = true;
        });
        if (!boolChk) {
            removeDataFilterAjax('color'); // bi remove url Attr
        } else {
            bindDataFilterAjax();
        }
    });
}

// Size click
function SizeItemClick() {
    $('.SizeFil ul li input[type=checkbox]').click(function () {
        var valueParam = '';
        var boolChk = false; //kiem tra xem co checked nao ko, neu ko co hien thi toan bo checked len

        $('.SizeFil ul li input[type=checkbox]:checked').each(function (index) {
            boolChk = true;
        });
        if (!boolChk) {
            removeDataFilterAjax('size'); // bi remove url Attr
        } else {
            bindDataFilterAjax();
        }
    });
}

// Attr click
function AttrItemClick() {
    $('.AttrFil ul li input[type=checkbox]').click(function () {
        var valueParam = '';
        var boolChk = false; //kiem tra xem co checked nao ko, neu ko co hien thi toan bo checked len

        $('.AttrFil ul li input[type=checkbox]:checked').each(function (index) {
            boolChk = true;
        });
        if (!boolChk) {
            removeDataFilterAjax('attr'); // bi remove url Attr
        } else {
            bindDataFilterAjax();
        }
    });
}
/*
    paramName: ten cua tham so
    isRemoveUrl: la kieu xoa url hay filter
        = true neu muon remove url
        = false neu muon loc binh thuong
*/
function bindDataFilterAjax() {
    // kiem tra toan bo cac param neu param nao co tham so loc thi ghep thanh url
    var p_price = '';
    var p_rate = '';
    var p_provider = '';
    var p_color = '';
    var p_size = '';
    var p_attr = '';
    var p_tabcate = '';
    var p_sort = '';
    var UrlReturn = '?';
    var page = 1;
    var cmdFill = $('.Category-p-list input#hidFillData');
    // price
    p_price = $('#hidpriceMin').val() + ';' + $('#hidpriceMax').val();
    // rate
    if ($('#rateValueMin').val() != undefined && $('#rateValueMax').val() != undefined) {
        p_rate = $('#rateValueMin').val() + ';' + $('#rateValueMax').val();
    }

    // provider
    var cmd = $('.ListProviderFil ul li input[type=checkbox]:checked');
    if (cmd != undefined) {
        cmd.each(function (index) {
            if (cmd.length == (index + 1)) {
                p_provider += this.value;
            } else {
                p_provider += this.value + ',';
            }
        });
    }

    // color
    var cmd = $('.ColorFil ul li input[type=checkbox]:checked');
    if (cmd != undefined) {
        cmd.each(function (index) {
            if (cmd.length == (index + 1)) {
                p_color += this.value;
            } else {
                p_color += this.value + ',';
            }
        });
    }

    // size
    var cmd = $('.SizeFil ul li input[type=checkbox]:checked');
    if (cmd != undefined) {
        cmd.each(function (index) {
            if (cmd.length == (index + 1)) {
                p_size += this.value;
            } else {
                p_size += this.value + ',';
            }
        });
    }

    // attr
    var cmd = $('.AttrFil ul li input[type=checkbox]:checked');
    if (cmd != undefined) {
        cmd.each(function (index) {
            if (cmd.length == (index + 1)) {
                p_attr += this.value;
            } else {
                p_attr += this.value + ',';
            }
        });
    }

    // active tab
    p_tabcate = $('.litsCo li a.tabFilActive').attr('idata');
    // sort
    p_sort = $('#selectSortCategory option:selected').val();

    $('#plvProductFilter').append('<div class="bg-fil-ajax"><img src="/images/icons/gif-load-small.gif" /></div>');
    // load data
    $.ajax({
        type: 'POST',
        dataType: 'html',
        data: { CategoryId: categoryId, Price: p_price, Rate: p_rate, Provider: p_provider, Color: p_color, Size: p_size, Attr: p_attr },
        cache: false,
        url: '/Category/AjaxProductFilterCategory',
        success: function (data) {
            $('#plvProductFilter .filContainer').html(data);
            // load slider
            LoadSliderPriceRange();
            // load rate slider
            LoadSliderRate();
            // Quick search
            quickSearchFilterbox();

            // set height provider
            setHeightProviderFilBox();
            // set height Color
            setHeightColorFilBox();
            // set kich thuoc cho box Size
            setHeightSizeFilBox();
            // set kich thuoc cho box Attr
            setHeightAttrFilBox();

            // ITEM CLICK 
            // provider click
            ProviderItemClick();
            // Color click
            ColorItemClick();
            // Size click
            SizeItemClick();
            // Attr click
            AttrItemClick();
            setTimeout(function () {
                $('#plvProductFilter .bg-fil-ajax').remove();
                $('html, body').animate({
                    scrollTop: ($(".Category-p-list").offset().top - 60)
                }, 600);
            }, 800);

            
        },
        error: function () {
            Console.log('Đã có lỗi xảy ra!');
        }
    });

    // load product
    $('.Category-p-list div.CoListProduct').append('<img id="CategoryLoadingTab" src="/images/icons/gif-load-small.gif" width="30" height="30" alt="loading category tab"/>');
    $.ajax({
        type: 'GET',
        dataType: 'html',
        data: { categoryId: categoryId, page: page, sortdrop: p_sort, catefil: p_tabcate, Price: p_price, Rate: p_rate, Provider: p_provider, Color: p_color, Size: p_size, Attr: p_attr },
        cache: false,
        url: '/Category/CategoryTabSelect',
        success: function (data) {
            setTimeout(function () {
                if (data != '') {
                    $('.Category-p-list div.CoListProduct').html(data);
                    $('.Category-p-list div.CoListProduct').append('<div id="plcPaggingCategoryAjax"></div>');
                    var totalrecord = $('#totalRecord-' + cmdFill.val().split('/')[1]);
                    var RecordByPage = totalrecord.parent().parent().find('.hidRecordByPage').val();
                    var spconlai = (parseInt(totalrecord.text()) - parseInt(RecordByPage));
                    if (spconlai <= 0) {
                        spconlai = 0;
                    }
                    $('.Category-p-list div.CoListProduct').append('<div class="pItem-pagging"><a href="javascript:void(0);" rel="nofollow">Xem thêm (còn <span id="productCountPage">' + spconlai + '</span> sản phẩm)</a></div>');
                    $('.Category-p-list div.CoListProduct #CategoryLoadingTab').remove();
                } else {
                    $('.Category-p-list div.CoListProduct').html('<div>Không có sản phẩm nào</div>');
                }
                paggingMore();
                //lazy load
                lzLoading();
            }, 200);
        },
        error: function () {
            Console.log('Đã có lỗi xảy ra!');
        }
    });


    // set url 
    if (p_price != '') {
        p_price = 'price=' + p_price + '&';
    }
    if (p_rate != '') {
        p_rate = 'rate=' + p_rate + '&';
    }
    if (p_provider != '') {
        p_provider = 'provider=' + p_provider + '&';
    }
    if (p_color != '') {
        p_color = 'color=' + p_color + '&';
    }
    if (p_size != '') {
        p_size = 'size=' + p_size + '&';
    }
    if (p_attr != '') {
        p_attr = 'attr=' + p_attr + '&';
    }
    if (p_tabcate != '') {
        p_tabcate = 'catefil=' + p_tabcate + '&';
    }
    if (p_sort != '') {
        p_sort = 'sortdrop=' + p_sort + '&';
    }

    UrlReturn += p_price + p_rate + p_provider + p_color + p_size + p_attr + p_tabcate + p_sort; // Url current filter
    if (p_price == '' && p_rate == '' && p_provider == '' && p_color == '' && p_size == '' && p_attr == '' && p_tabcate == '' && p_sort == '') {
        UrlReturn = '';
    }
    // set url default
    if (UrlReturn == '') {
        var url = $(location).attr('href');
        var urlParam = url.split('?');
        UrlReturn = urlParam[0] + '?';
    }
    window.history.replaceState(null, null, UrlReturn.substring(0, UrlReturn.length - 1));

}

function removeDataFilterAjax(paramName) {
    // kiem tra toan bo cac param neu param nao co tham so loc thi ghep thanh url
    var p_price = '';
    var p_rate = '';
    var p_provider = '';
    var p_color = '';
    var p_size = '';
    var p_attr = '';
    var p_tabcate = '';
    var p_sort = '';
    var UrlReturn = '?';
    var page = 1;
    var cmdFill = $('.Category-p-list input#hidFillData');
    //// price
    //if (paramName != 'price') {
    //    p_price = $('#hidpriceMin').val() + ';' + $('#hidpriceMax').val();
    //}

    //// rate
    //if (paramName != 'rate') {
    //    p_rate = $('#rateValueMin').val() + ';' + $('#rateValueMax').val();
    //}

    // provider
    if (paramName != 'provider') {
        var cmd = $('.ListProviderFil ul li input[type=checkbox]:checked');
        if (cmd != undefined) {
            cmd.each(function (index) {
                if (cmd.length == (index + 1)) {
                    p_provider += this.value;
                } else {
                    p_provider += this.value + ',';
                }
            });
        }

    }

    // color
    if (paramName != 'color') {
        var cmd = $('.ColorFil ul li input[type=checkbox]:checked');
        if (cmd != undefined) {
            cmd.each(function (index) {
                if (cmd.length == (index + 1)) {
                    p_color += this.value;
                } else {
                    p_color += this.value + ',';
                }
            });
        }

    }

    // size
    if (paramName != 'size') {
        var cmd = $('.SizeFil ul li input[type=checkbox]:checked');
        if (cmd != undefined) {
            cmd.each(function (index) {
                if (cmd.length == (index + 1)) {
                    p_size += this.value;
                } else {
                    p_size += this.value + ',';
                }
            });
        }

    }

    // attr
    if (paramName != 'attr') {
        var cmd = $('.AttrFil ul li input[type=checkbox]:checked');
        if (cmd != undefined) {
            cmd.each(function (index) {
                if (cmd.length == (index + 1)) {
                    p_attr += this.value;
                } else {
                    p_attr += this.value + ',';
                }
            });
        }

    }

    // active tab
    if (paramName != 'catefil') {
        p_tabcate = $('.litsCo li a.tabFilActive').attr('idata');
    }
    // sort
    if (paramName != 'sortdrop') {
        p_sort = $('#selectSortCategory option:selected').val();
    }
    $('#plvProductFilter').append('<div class="bg-fil-ajax"><img src="/images/icons/gif-load-small.gif" width="30" height="30" /></div>');
    // load data
    $.ajax({
        type: 'POST',
        dataType: 'html',
        data: { CategoryId: categoryId, Price: p_price, Rate: p_rate, Provider: p_provider, Color: p_color, Size: p_size, Attr: p_attr },
        cache: false,
        url: '/Category/AjaxProductFilterCategory',
        success: function (data) {

            $('#plvProductFilter .filContainer').html(data);

            // load slider
            LoadSliderPriceRange();
            // load rate slider
            LoadSliderRate();
            // Quick search
            quickSearchFilterbox();

            // set height provider
            setHeightProviderFilBox();
            // set height Color
            setHeightColorFilBox();
            // set kich thuoc cho box Size
            setHeightSizeFilBox();
            // set kich thuoc cho box Attr
            setHeightAttrFilBox();

            // ITEM CLICK 
            // provider click
            ProviderItemClick();
            // Color click
            ColorItemClick();
            // Size click
            SizeItemClick();
            // Attr click
            AttrItemClick();
            setTimeout(function () {
                $('#plvProductFilter .bg-fil-ajax').remove();
                $('html, body').animate({
                    scrollTop: ($(".Category-p-list").offset().top - 60)
                }, 600);
            }, 800);

        },
        error: function () {
            Console.log('Đã có lỗi xảy ra!');
        }
    });

    // load product
    $('.Category-p-list div.CoListProduct').append('<img id="CategoryLoadingTab" src="/images/icons/gif-load-small.gif" width="30" height="30" alt="loading category tab"/>');
    $.ajax({
        type: 'GET',
        dataType: 'html',
        data: { categoryId: categoryId, page: page, sortdrop: p_sort, catefil: p_tabcate, Price: p_price, Rate: p_rate, Provider: p_provider, Color: p_color, Size: p_size, Attr: p_attr },
        cache: false,
        url: '/Category/CategoryTabSelect',
        success: function (data) {
            setTimeout(function () {
                if (data != '') {
                    $('.Category-p-list div.CoListProduct').html(data);
                    $('.Category-p-list div.CoListProduct').append('<div id="plcPaggingCategoryAjax"></div>');
                    var totalrecord = $('#totalRecord-' + cmdFill.val().split('/')[1]);
                    var RecordByPage = totalrecord.parent().parent().find('.hidRecordByPage').val();
                    var spconlai = (parseInt(totalrecord.text()) - parseInt(RecordByPage));
                    if (spconlai <= 0) {
                        spconlai = 0;
                    }
                    $('.Category-p-list div.CoListProduct').append('<div class="pItem-pagging"><a href="javascript:void(0);" rel="nofollow">Xem thêm (còn <span id="productCountPage">' + spconlai + '</span> sản phẩm)</a></div>');
                    $('.Category-p-list div.CoListProduct #CategoryLoadingTab').remove();
                } else {
                    $('.Category-p-list div.CoListProduct').html('<div>Không có sản phẩm nào</div>');
                }
                paggingMore();

                //lazy load
                lzLoading();
            }, 200);
        },
        error: function () {
            Console.log('Đã có lỗi xảy ra!');
        }
    });

    // set url 
    if (p_price != '') {
        p_price = 'price=' + p_price + '&';
    }
    if (p_rate != '') {
        p_rate = 'rate=' + p_rate + '&';
    }
    if (p_provider != '') {
        p_provider = 'provider=' + p_provider + '&';
    }
    if (p_color != '') {
        p_color = 'color=' + p_color + '&';
    }
    if (p_size != '') {
        p_size = 'size=' + p_size + '&';
    }
    if (p_attr != '') {
        p_attr = 'attr=' + p_attr + '&';
    }
    if (p_tabcate != '') {
        p_tabcate = 'catefil=' + p_tabcate + '&';
    }
    if (p_sort != '') {
        p_sort = 'sortdrop=' + p_sort + '&';
    }

    UrlReturn += p_price + p_rate + p_provider + p_color + p_size + p_attr + p_tabcate + p_sort; // Url current filter
    if (p_price == '' && p_rate == '' && p_provider == '' && p_color == '' && p_size == '' && p_attr == '' && p_tabcate == '' && p_sort == '') {
        UrlReturn = '';
    }
    // set url default
    if (UrlReturn == '') {
        var url = $(location).attr('href');
        var urlParam = url.split('?');
        UrlReturn = urlParam[0] + '?';
    }
    window.history.replaceState(null, null, UrlReturn.substring(0, UrlReturn.length - 1));

}
